//
//  ActivityTableViewController.m
//  SXH
//
//  Created by Jack on 15/10/21.
//  Copyright © 2015年 lyss. All rights reserved.
//

#import "ActivityTableViewController.h"
#import "activityTableViewCell.h"
#import "WebViewController.h"
#import "UIImageView+WebCache.h"
#import "UIImageView+LK.h"
#import "CommonService.h"
#import "YYAnimationIndicator.h"
#import "MJRefresh.h"

@interface ActivityTableViewController (){
    YYAnimationIndicator *indicator;
    
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
}
@property (weak, nonatomic) IBOutlet UITableView *activityTableView;
@property (nonatomic, strong) NSMutableArray *mutableArrayActivity;
@end

@implementation ActivityTableViewController
@synthesize parkEntity;
@synthesize activityTableView;
@synthesize mutableArrayActivity;

- (void)viewDidLoad {
    [super viewDidLoad];
    mutableArrayActivity = [[NSMutableArray alloc]init];
    page = 1;
    [self addHeader];
    [self addFooter];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [mutableArrayActivity count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"activityTableViewCell";
    activityTableViewCell *cell = (activityTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"activityTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    cell.activityName.text = [[mutableArrayActivity objectAtIndex:indexPath.row] objectForKey:@"title"];
    cell.activityIntroduce.text= [[mutableArrayActivity objectAtIndex:indexPath.row] objectForKey:@"description"];
    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", IMAGE_URL, [[mutableArrayActivity objectAtIndex:indexPath.row] objectForKey:@"album_thumb"]];
    cell.activityImage.imageURL=[NSURL URLWithString:imageUrl];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 81;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //当手指离开某行时，就让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = [[mutableArrayActivity objectAtIndex:indexPath.row] valueForKeyPath:@"html"];
    vc.vcTitle = [[mutableArrayActivity objectAtIndex:indexPath.row] valueForKeyPath:@"title"];
    [[SDWebImageManager sharedManager]downloadImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", IMAGE_URL, [[mutableArrayActivity objectAtIndex:indexPath.row] objectForKey:@"album_thumb"]]] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        vc.imageShare = image;}];
    vc.contentShare = [[mutableArrayActivity objectAtIndex:indexPath.row] objectForKey:@"description"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void) getActivityData:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    indicator = [[YYAnimationIndicator alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-40, self.view.frame.size.height/2-40, 80, 57)];
    [indicator setLoadText:Loading_Text];
    [self.view addSubview:indicator];
    
    [indicator startAnimation];  //开始转动
    
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    //读取本地数据库是否有该文件
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           parkEntity.ID, @"parkid",
                           strPageNo,@"page",
                           @"10", @"limit",nil];
    
    [service getNetWorkData:param
                       Path:PARK_ACTIVITY
                  Successed:^(id entity) {
                      if (pageNo ==1) {
                          [mutableArrayActivity removeAllObjects];
                          page = 1;
                      }
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      
                      for (NSDictionary* attributes in array) {
                          [mutableArrayActivity addObject:attributes];
                      }
                      [indicator stopAnimationWithLoadText:HasLoaded_Text withType:YES];
                      [self doneWithView:refreshView];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:refreshView];
                      [indicator stopAnimationWithLoadText:LoadFail_Text withType:YES];
                  }];
}

- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.activityTableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getActivityData:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.activityTableView;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [self getActivityData:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.activityTableView reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ActivityTableViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ActivityTableViewController"];
}

@end
